package com.quwan.job.impl;

import com.alibaba.fastjson.JSONObject;
import com.quwan.app.service.impl.OrderServiceImpl;
import com.quwan.constans.CacheKey;
import com.quwan.entity.TFinanceData;
import com.quwan.entity.TMsgRecord;
import com.quwan.entity.TPreserveData;
import com.quwan.entity.TSpreadData;
import com.quwan.job.AbstractJobs;
import com.quwan.mapper.*;
import com.quwan.utils.DateUtils;
import com.quwan.utils.redis.Redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 * @author quan
 * @date 2021-07-27 15:34
 */
@Component
public class SpreadDataCountJobs extends AbstractJobs {
    private TSpreadDataMapper spreadDataMapper;
    private TPreserveDataMapper preserveDataMapper;
    private TFinanceDataMapper financeDataMapper;
    private TMsgRecordMapper msgRecordMapper;
    private Redis redis;

    @Autowired
    public SpreadDataCountJobs(Redis redis,
                               @NotNull JobRunStateInfoMapper jobRunStateInfoMapper,
                               TSpreadDataMapper spreadDataMapper,
                               TPreserveDataMapper preserveDataMapper,
                               TFinanceDataMapper financeDataMapper,
                               TMsgRecordMapper msgRecordMapper) {
        super(jobRunStateInfoMapper);
        this.spreadDataMapper = spreadDataMapper;
        this.preserveDataMapper = preserveDataMapper;
        this.financeDataMapper = financeDataMapper;
        this.msgRecordMapper = msgRecordMapper;
        this.redis = redis;
        // name = "推广数据统计";
    }

    @Override
    protected String ExecuteTask() throws Exception {
        TSpreadData res = spreadDataMapper.getCurrentSomeData();
        Long handleCount = OrderServiceImpl.handle_order_count.get();
        OrderServiceImpl.handle_order_count.set(0);
        if (spreadDataMapper.insert(
                new TSpreadData()
                        .setDay(new Date())
                        .setVisitor(res.getAccess() + res.getVisitor())
                        .setAccess(res.getAccess() + res.getVisitor() + res.getLogin())
                        .setLogin(res.getLogin())
                        .setActive(res.getActive())
                        .setCancelOrder(res.getCancelOrder())
                        .setConsumerOrder(handleCount.intValue())
                        .setRegister(res.getRegister())
                        .setTranfer(res.getTranfer())
                        .setPublishOrder(res.getPublishOrder()))
                != 1) {
            throw new Exception("spreadData insert  err");
        }
        return DateUtils.getLocalDateTimeStr() + ":推广数据统计成功";

    }

    /**
     * 留存报表 统计
     *
     * @return
     * @throws Exception
     */
    @Override
    protected String preserveDataExecuteTask() throws Exception {
        Date date = DateUtils.getNowDate();
        String nowTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", date);
        TPreserveData preserve = preserveDataMapper.getPreserveData(nowTime);
        preserve.setDay(date);
        preserve.setAddTime(date);
        TPreserveData pr = preserveDataMapper.selectPreserveDataByTime(nowTime);
        if (pr != null) {
            preserve.setId(pr.getId());
            preserveDataMapper.updateById(preserve);
        } else {
            preserveDataMapper.insert(preserve);
        }
        IntStream.rangeClosed(1, 30).parallel().forEach(i -> {
            Date current = DateUtils.getDatePlus(date, -i);
            String curTime = DateUtils.parseDateToStr("yyyy-MM-dd", current);
            TPreserveData pre = preserveDataMapper.selectPreserveDataByTime(curTime);
            if (pre != null) {
                TPreserveData preData = preserveDataMapper.getPreserveData(curTime);
                preData.setId(pre.getId());
                preData.setDay(current);
                preserveDataMapper.updateById(preData);
            }
        });

        return DateUtils.getLocalDateTimeStr() + ":留存报表数据统计成功";

    }

    //财务报表 数据统计
    @Override
    protected String financeDataExecuteTask() throws Exception {
        LocalDate day = LocalDate.now().minusDays(1);
        //DONE: 提现抽成未完成
        TFinanceData financeData = financeDataMapper.selectFinanceData(day);
        if (financeDataMapper
                .insert(
                        financeData
                                .setDay(day)
                                .setCompanyGet(financeData.getVipMoney()
                                        .add(financeData.getTransferGet())
                                        .add(financeData.getCompanyCommission())))
                != 1)
            throw new Exception("financeDataExecuteTask insert  err");
        return DateUtils.getLocalDateTimeStr() + ":财务报表数据统计成功";
    }

    @Override
    protected String syncChatMsgExecuteTask() throws Exception {
        //同步前一天的聊天记录
        String date = LocalDate.now().minusDays(1).toString();
        String key = CacheKey.IM.record + date;
        Long count = redis.zCard(key);
        long countNum = count;

        if (count == 0){
            redis.del(key);
            return DateUtils.getLocalDateTimeStr()+":"+date + "缓存消息记录为空";
        }

        int pageNo = 1;
        int pageSize = 1000;
        do {
            int start = (pageNo - 1) * pageSize;
            Set<Object> values = redis.zRange(key, start, start + pageSize - 1);

            List<TMsgRecord> msgRecords = values.parallelStream().map(val -> {
                String valJson = String.valueOf(val);
                TMsgRecord msg = JSONObject.parseObject(valJson, TMsgRecord.class);
                msg.setSessionKey(String.valueOf(msg.getSender() + msg.getReceiver())).setStatus(0);
                return msg;
            }).collect(Collectors.toList());

            msgRecordMapper.insertBatchSomeColumn(msgRecords);

            count -= pageSize;
            pageNo++;
        } while (count > 0);
        redis.del(key);
        return  DateUtils.getLocalDateTimeStr()+":"+date + "同步缓存聊天记录成功(" + countNum + ")条";
    }
}
